package com.lzc.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.impl.JWTParser;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * JWT 加密 解析工具类
 */
public class JwtUtil {

    private static final String key = "lzc";

    // 根据uid生成JWT令牌
    public static String createJwt(Long uid){

        return JWT.create()
                .withClaim("uid", uid)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + 3600 * 1000))
                .sign(Algorithm.HMAC256(key));

    }

    // 根据JWT解析uid
    public static Long getUid(String jwt){

        Claim claim = null;
        try {
            JWT.require(Algorithm.HMAC256(key)).build().verify(jwt);
            DecodedJWT decode = JWT.decode(jwt);
            claim = decode.getClaim("uid");
        } catch (Exception e){
            return null;
        }
        return claim.asLong();

    }

    public static void main(String[] args) {
        System.out.println(createJwt(1L));
//        System.out.println(createJwt(2L));
//
//        String username = "2313Ad2&";
//        System.out.println(username.matches("^[a-zA-Z0-9_]+$"));
    }
}
